package com.example.qsmx;

import com.example.qsmx.Util.MyDBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.UUID;

@WebServlet("/modify-value")
@MultipartConfig
public class ModifyQSMX extends HttpServlet {
    public java.sql.Date stringTSql(String utilData) throws ParseException {
        // 将用户没有输入的东西给予固定值
        // 如果用户没有填写这个属性，那就将这个值设定为 2004-09-09
        // 但是也有可能输入的是 " " 不能够使用，所以还要确保不为空
        if (utilData == null || utilData.trim().isEmpty()) {
            utilData = "2004-09-09";
        }
        // 我们有一个String类型的日期

        // 创建一个SimpleDateFormat对象，并设置日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 使用SimpleDateFormat对象解析String类型的日期
        Date utilDate = sdf.parse(utilData);

        // 将java.util.Date转换为java.sql.Date
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        // 将数据库的 date 返回
        return sqlDate;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        // 获取前端的输入
        int id = Integer.valueOf(req.getParameter("idd"));
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String userAccount = req.getParameter("userAccount");

        // 自动添加修改时间
        LocalDate createUserDate = LocalDate.now();
        java.sql.Date sqlCreateUserDate;
        try {
            sqlCreateUserDate = stringTSql(createUserDate.toString());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        // 要上传到哪里
        String uploadPath = getServletContext().getRealPath("/") + "uploads";

        // 处理文件上传 - start
        Part filePart = req.getPart("cover");
        String coverFileName = null;

        // 判断用户有没有上传封面图
        if (filePart != null && filePart.getSize() > 0) {
            // 获取原始文件名和扩展名
            String originalFileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));

            // 生成新的文件名：时间戳_UUID.扩展名
            String newFileName = System.currentTimeMillis() + "_" +
                    UUID.randomUUID().toString().substring(0, 8) +
                    fileExtension;

            // 检查 uploads 文件夹是否存在，如果不存在，自动创建
            Path uploadsPath = Paths.get(uploadPath);
            if (!Files.exists(uploadsPath)) {
                Files.createDirectories(uploadsPath);
            }

            // 使用新文件名保存文件
            File uploadedFile = new File(uploadPath, newFileName);
            filePart.write(uploadedFile.getAbsolutePath());
            coverFileName = "uploads/" + newFileName;
        }


        // 处理文件修改 - end

        try {
            modifyBlog(id, title, content, sqlCreateUserDate, userAccount, coverFileName);
            req.getRequestDispatcher("WEB-INF/interface.jsp").forward(req, resp);
        } catch (ServletException e) {
            // 如果添加失败，删除已上传的封面图
            if (coverFileName != null) {
                File uploadedFile = new File(getServletContext().getRealPath("/") + coverFileName);
                if (uploadedFile.exists()) {
                    uploadedFile.delete();
                }
            }
            throw e;
        }
    }

    private void modifyBlog(int id, String title, String content, java.sql.Date sqlCreateUserDate, String userAccount, String coverFileName) throws ServletException {
        try (Connection conn = MyDBUtil.getConnection()) {
            String sql;
            if (coverFileName != null) {
                sql = "UPDATE qsmxvalue SET `value-tittle` = ?, `value-content` = ?, `value-create-time` = ?,`value-userAccount` = ?,`value-cover` = ?   WHERE `value-id` = ?";
            } else {
                sql = "UPDATE qsmxvalue SET `value-tittle` = ?, `value-content` = ?, `value-create-time` = ?,`value-userAccount` = ? WHERE `value-id` = ?";
            }

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, title);
                stmt.setString(2, content);
                stmt.setDate(3, sqlCreateUserDate);
                stmt.setString(4, userAccount);
                if (coverFileName != null) {
                    stmt.setString(5, coverFileName);
                    stmt.setInt(6, id);
                }else {
                    stmt.setInt(5, id);
                }
                stmt.executeUpdate();
            }
        } catch (SQLException e) {
            throw new ServletException("修改博客失败", e);
        }
    }


}
